package com.stars.easyms.alarm.client.dingtalk;

import com.stars.easyms.alarm.message.EasyMsAlarmMessage;
import com.stars.easyms.alarm.client.EasyMsAlarmClient;
import com.stars.easyms.alarm.client.dingtalk.robot.EasyMsDingTalkRobotClient;
import com.stars.easyms.alarm.constant.EasyMsAlarmConstant;
import com.stars.easyms.alarm.exception.EasyMsAlarmRuntimeException;
import com.stars.easyms.alarm.properties.EasyMsAlarmProperties;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>className: EasyMsDingTalkAlarmClient</p>
 * <p>description: 钉钉告警客户端</p>
 *
 * @author guoguifang
 * @version 1.6.1
 * @date 2020/8/22 3:53 下午
 */
public final class EasyMsDingTalkAlarmClient implements EasyMsAlarmClient {

    private EasyMsAlarmProperties.DingTalk dingTalkAlarmProperties;

    private Map<String, EasyMsDingTalkRobotClient> dingTalkRobotClientMap = new HashMap<>(8);

    private static final String DEFAULT_CLIENT_ID = "default";

    public EasyMsDingTalkAlarmClient(EasyMsAlarmProperties alarmProperties) {
        this.dingTalkAlarmProperties = alarmProperties.getDingTalk();
    }

    @Override
    public void sendAlarmMessage(EasyMsAlarmMessage easyMsAlarmMessage) throws Exception {
        // 获取到告警客户端ID，如果没有指定则使用默认的
        String clientId = StringUtils.isBlank(easyMsAlarmMessage.getClientId()) ? DEFAULT_CLIENT_ID : easyMsAlarmMessage.getClientId().trim();
        EasyMsDingTalkRobotClient dingTalkClient = dingTalkRobotClientMap.get(clientId);
        if (dingTalkClient == null) {
            throw new EasyMsAlarmRuntimeException("找不到钉钉机器人客户端(id:{})，请检查配置是否正确！", clientId);
        }

        dingTalkClient.sendAlarmMessage(easyMsAlarmMessage);
    }

    @Override
    public String getClientType() {
        return EasyMsAlarmConstant.DING_TALK;
    }

    @Override
    public boolean initAndReturnIsValid() {
        if (dingTalkAlarmProperties.isEnabled()) {
            String defaultRobotUrl = dingTalkAlarmProperties.getRobotUrl();
            String defaultRobotSecret = dingTalkAlarmProperties.getRobotSecret();
            if (!StringUtils.isEmpty(defaultRobotUrl) && !StringUtils.isEmpty(defaultRobotSecret)) {
                dingTalkRobotClientMap.put(DEFAULT_CLIENT_ID,
                        new EasyMsDingTalkRobotClient(DEFAULT_CLIENT_ID, defaultRobotUrl, defaultRobotSecret));
            }
            dingTalkAlarmProperties.getRobots().forEach(d -> {
                String id = d.getId();
                String url = d.getUrl();
                String secret = d.getSecret();
                if (!StringUtils.isEmpty(id) && !StringUtils.isEmpty(url) && !StringUtils.isEmpty(secret)) {
                    dingTalkRobotClientMap.put(id, new EasyMsDingTalkRobotClient(id, url, secret));
                }
            });
        }
        return !dingTalkRobotClientMap.isEmpty();
    }

}
